<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends MY_Controller {
	
	public function __construct() {
		parent::__construct();
		$this->load->model('Karas_model');
		$this->load->library('pagination');
		$this->load->library('session');
	}
	
	public function index() {
		$this->view['template'] = 'index/index';
		$data = $this->Karas_model->get_limit($this->per_page, 
				$this->uri->segment(4) ? $this->uri->segment(4) :0);
		
		$this->view['data'] = array (
			'songs' 		=> $data->result_array(),
			'pagination'	=> $this->_pagination(
				'index/index/page',
				$this->Karas_model->count_all(),
				$this->per_page,
				4	
			),
			'keyword' 		=> ''			
		);
		
		$this->_render($this->view);		
	}
	
	public function search() {
		$key = str_replace('+', ' ', $this->input->get('keyword'));
		$this->view['template'] = 'index/index';
		$page = $this->input->get('page');
		
		$offset = $page ? ($page - 1) * $this->per_page : 0;
		
		$data = $this->Karas_model->search($key, " LIMIT {$this->per_page} offset {$offset}");
		
		if ($this->input->is_ajax_request()) {
			echo json_encode($data->result_array());
			exit;
		}
		
		$this->view['data'] = array (
				'songs'  		=> $data->result_array(),
				'pagination'	=> $this->_pagination(
							'index/search/?keyword='. $key,
							$this->Karas_model->count_all_search($key),
							$this->per_page,
							4,
							true
						),
				'keyword'		=> $key
		);
		$this->_render($this->view);
	}
}